package com.fruit.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.apache.commons.lang3.StringUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * 权重
 * 
 * @author Administrator
 * @version 2017.12.01 11:40
 */
@Slf4j
public class RouteUtil {

	public static class Node {
		private String node;
		private int min;
		private int max;

		Node(String node, int min, int max) {
			log.info("权重参数node:{},min:{},max{}", node, min, max);
			this.node = node;
			this.min = min;
			this.max = max;
		}

		boolean contains(int num) {
			if (num >= min && num < max) {
				return true;
			} else {
				return false;
			}
		}
	}

	public static String getNode(String value, String route) {

		return getNode(StringUtils.split(value, ","), StringUtils.split(route, ","));

	}

	public static String getNode(String[] value, String[] route) {
		List<Node> nodes = new ArrayList<>();
		int min = 0;
		for (int i = 0; i < value.length; i++) {
			int max = min + Integer.parseInt(route[i]);
			nodes.add(new Node(value[i], min, max));
			min = max;
		}
		log.info("最大值:{}", min);
		if(min == 0){
			min = 1;
		}
		int r = new Random().nextInt(min);
		log.info("随机数:{}", r);
		for (Node n : nodes) {
			if (n.contains(r)) {
				return n.node;
			}
		}
		return null;

	}

	public static String getNode(String[] value) {
		int r = new Random().nextInt(value.length);
		return value[r];
	}

}